package com.yupfeg.executor

import java.util.concurrent.ThreadFactory
import java.util.concurrent.atomic.AtomicInteger

/**
 * 默认实现的线程构造工厂类
 * @author yuPFeG
 * @date 2022/01/16
 *
 * @param prefix 线程名称前缀
 * @param isDaemon 是否作为守护线程
 */
class DefaultThreadFactory(
    private val prefix : String? = null,
    private val isDaemon : Boolean = false
) : ThreadFactory{

    companion object{
        /**线程池数量*/
        private val poolNumber = AtomicInteger(0)
    }

    private val mThreadGroup : ThreadGroup
    private val threadNumber = AtomicInteger(1)
    private val mThreadNamePrefix : String

    init {
        val s = System.getSecurityManager()
        mThreadGroup = s?.threadGroup ?: Thread.currentThread().threadGroup!!
        poolNumber.getAndIncrement()
        mThreadNamePrefix = getDefaultThreadPoolName()
    }

    private fun getDefaultThreadPoolName() : String{
        return "ExecutorProvider-${prefix ?: poolNumber.get()}-Thread"
    }

    override fun newThread(r: Runnable?): Thread {
        val t = Thread(
            mThreadGroup, r,
            "$mThreadNamePrefix-${threadNumber.getAndIncrement()}",
            0
        )
        if (t.isDaemon) {
            t.isDaemon = isDaemon
        }

        //线程优先级调整为默认，避免抢占主线程CPU时间片
        if (t.priority < Thread.NORM_PRIORITY){
            t.priority = Thread.NORM_PRIORITY
        }

        return t
    }
}